<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="仓库名称" prop="name">
        <el-input v-model="searchForm.name" placeholder="请输入仓库名称" clearable />
      </el-form-item>
      <el-form-item label="仓库编号" prop="code">
        <el-input v-model="searchForm.code" placeholder="请输入仓库编号" clearable />
      </el-form-item>
      <el-form-item label="仓库类型" prop="type">
        <el-select v-model="searchForm.type" placeholder="请选择仓库类型" clearable>
          <el-option label="普通仓库" :value="1" />
          <el-option label="冷藏仓库" :value="2" />
          <el-option label="危险品仓库" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="仓库状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择仓库状态" clearable>
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="resetSearch">
          <el-icon><Refresh /></el-icon> 重置
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 新增仓库
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="warehouseList"
      border
      v-loading="loading"
      class="custom-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="仓库编号" width="100" align="center" />
      <el-table-column prop="code" label="仓库编号" width="120" align="center" />
      <el-table-column prop="name" label="仓库名称" min-width="150" align="center" />
      <el-table-column prop="type" label="仓库类型" width="120" align="center">
        <template #default="{ row }">
          <el-tag :type="getWarehouseTypeTag(row.type)">
            {{ getWarehouseTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="仓库地址" min-width="200" align="center" />
      <el-table-column prop="manager" label="仓库管理员" width="120" align="center" />
      <el-table-column prop="phone" label="联系电话" width="130" align="center" />
      <el-table-column prop="area" label="仓库面积" width="120" align="center">
        <template #default="{ row }"> {{ row.area }}m² </template>
      </el-table-column>
      <el-table-column prop="capacity" label="仓库容量" width="120" align="center">
        <template #default="{ row }"> {{ row.capacity }}m³ </template>
      </el-table-column>
      <el-table-column prop="status" label="仓库状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'" effect="plain">
            {{ row.status === 1 ? "正常" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" align="center" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)"> 编辑 </el-button>
          <el-button type="primary" link @click="handleViewStock(row)"> 库存 </el-button>
          <el-button type="primary" link @click="handleViewRecords(row)"> 出入库记录 </el-button>
          <el-button type="danger" link @click="handleDelete(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="page.total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑仓库对话框 -->
    <el-dialog :title="dialogType === 'add' ? '新增仓库' : '编辑仓库'" v-model="dialogVisible" width="500px">
      <el-form :model="warehouseForm" :rules="rules" ref="warehouseFormRef" label-width="100px">
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="warehouseForm.name" placeholder="请输入仓库名称" />
        </el-form-item>
        <el-form-item label="仓库编号" prop="code">
          <el-input v-model="warehouseForm.code" placeholder="请输入仓库编号" />
        </el-form-item>
        <el-form-item label="仓库类型" prop="type">
          <el-select v-model="warehouseForm.type" placeholder="请选择仓库类型">
            <el-option label="普通仓库" :value="1" />
            <el-option label="冷藏仓库" :value="2" />
            <el-option label="危险品仓库" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input v-model="warehouseForm.address" placeholder="请输入仓库地址" />
        </el-form-item>
        <el-form-item label="管理员" prop="manager">
          <el-input v-model="warehouseForm.manager" placeholder="请输入管理员姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="warehouseForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="仓库面积" prop="area">
          <el-input-number
            v-model="warehouseForm.area"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="请输入仓库面积(m²)"
          />
        </el-form-item>
        <el-form-item label="仓库容量" prop="capacity">
          <el-input-number
            v-model="warehouseForm.capacity"
            :min="0"
            :precision="2"
            :step="10"
            placeholder="请输入仓库容量(m³)"
          />
        </el-form-item>
        <el-form-item label="仓库状态" prop="status">
          <el-radio-group v-model="warehouseForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="仓库描述" prop="description">
          <el-input v-model="warehouseForm.description" type="textarea" :rows="3" placeholder="请输入仓库描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存详情对话框 -->
    <el-dialog title="库存详情" v-model="stockDialogVisible" width="800px">
      <el-table :data="stockList" border>
        <el-table-column prop="productName" label="商品名称" />
        <el-table-column prop="stock" label="库存数量" width="100" align="center" />
        <el-table-column prop="minStock" label="最小库存" width="100" align="center" />
        <el-table-column prop="maxStock" label="最大库存" width="100" align="center" />
        <el-table-column prop="location" label="库位" width="100" align="center" />
      </el-table>
    </el-dialog>

    <!-- 出入库记录对话框 -->
    <el-dialog title="出入库记录" v-model="recordDialogVisible" width="900px">
      <el-table :data="stockRecords" border>
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column prop="type" label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.type === '1' || row.type === 1 ? 'success' : 'warning'">
              {{ row.type === "1" || row.type === 1 ? "入库" : "出库" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" align="center" />
        <el-table-column prop="operatorName" label="操作人" width="100" align="center" />
        <el-table-column prop="operationTime" label="操作时间" width="180" align="center" />
        <el-table-column prop="remark" label="备注" min-width="150" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Refresh } from "@element-plus/icons-vue";
import {
  getWarehouseList,
  getWarehouseDetail,
  addWarehouse,
  updateWarehouse,
  deleteWarehouse,
  getWarehouseStock,
  getStockRecords,
} from "@/api/warehouse";

// 搜索表单数据
const searchForm = reactive({
  name: "",
  code: "",
  type: null,
  status: null,
});

// 表单数据
const warehouseForm = reactive({
  id: null,
  name: "",
  code: "",
  address: "",
  manager: "",
  phone: "",
  area: 0,
  capacity: 0,
  type: 1,
  status: 1,
  description: "",
});

// 表单校验规则
const rules = {
  name: [{ required: true, message: "请输入仓库名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入仓库编号", trigger: "blur" }],
  address: [{ required: true, message: "请输入仓库地址", trigger: "blur" }],
  manager: [{ required: true, message: "请输入管理员姓名", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  area: [{ required: true, message: "请输入仓库面积", trigger: "blur" }],
  capacity: [{ required: true, message: "请输入仓库容量", trigger: "blur" }],
  type: [{ required: true, message: "请选择仓库类型", trigger: "change" }],
  status: [{ required: true, message: "请选择仓库状态", trigger: "change" }],
};

// 获取仓库类型标签类型
const getWarehouseTypeTag = (type) => {
  switch (type) {
    case 1:
      return "";
    case 2:
      return "info";
    case 3:
      return "warning";
    default:
      return "";
  }
};

// 获取仓库类型文本
const getWarehouseTypeText = (type) => {
  switch (type) {
    case 1:
      return "普通仓库";
    case 2:
      return "冷藏仓库";
    case 3:
      return "危险品仓库";
    default:
      return "未知类型";
  }
};
// 分页数据
const page = reactive({
  current: 1,
  size: 10,
  total: 0,
});

// 表格数据
const warehouseList = ref([]);
const loading = ref(false);
const selectedWarehouses = ref([]);

// 对话框数据
const dialogVisible = ref(false);
const dialogType = ref("add");

// 库存相关数据
const stockDialogVisible = ref(false);
const stockList = ref([]);
const recordDialogVisible = ref(false);
const stockRecords = ref([]);

// 获取仓库列表
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: page.current,
      size: page.size,
    };
    const { data } = await getWarehouseList(params);
    warehouseList.value = data.list;
    page.total = data.total;
  } catch (error) {
    console.error("获取仓库列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  page.current = 1;
  getList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = "";
  searchForm.code = "";
  searchForm.status = null;
  searchForm.type = null;
  handleSearch();
};

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedWarehouses.value = selection;
};

// 新增仓库
const handleAdd = () => {
  dialogType.value = "add";
  Object.assign(warehouseForm, {
    id: null,
    name: "",
    address: "",
    manager: "",
    phone: "",
    capacity: 0,
    status: 1,
  });
  dialogVisible.value = true;
};

// 编辑仓库
const handleEdit = async (row) => {
  dialogType.value = "edit";
  const { data } = await getWarehouseDetail(row.id);
  Object.assign(warehouseForm, data);
  dialogVisible.value = true;
};

// 提交表单
const warehouseFormRef = ref(null);
const handleSubmit = async () => {
  if (!warehouseFormRef.value) return;
  await warehouseFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await addWarehouse(warehouseForm);
          ElMessage.success("添加成功");
        } else {
          await updateWarehouse(warehouseForm);
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("保存仓库失败:", error);
      }
    }
  });
};

// 删除仓库
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该仓库吗？", "提示", {
    type: "warning",
  }).then(async () => {
    try {
      await deleteWarehouse(row.id);
      ElMessage.success("删除成功");
      getList();
    } catch (error) {
      console.error("删除仓库失败:", error);
    }
  });
};

// 查看库存
const handleViewStock = async (row) => {
  try {
    const { data } = await getWarehouseStock(row.id);
    stockList.value = data;
    stockDialogVisible.value = true;
  } catch (error) {
    console.error("获取库存信息失败:", error);
  }
};

// 查看出入库记录
const handleViewRecords = async (row) => {
  try {
    const { data } = await getStockRecords({ warehouseId: row.id });
    stockRecords.value = data;
    recordDialogVisible.value = true;
  } catch (error) {
    console.error("获取出入库记录失败:", error);
  }
};

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val;
  getList();
};

// 当前页变化
const handleCurrentChange = (val) => {
  page.current = val;
  getList();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .search-form {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .table-operations {
    margin-bottom: 20px;
  }

  .custom-table {
    margin-bottom: 20px;
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
  border-top: 1px solid #dcdfe6;
}
</style>
